from flask_restplus import Namespace, Resource
from .auth import auth, g
from flask import request
from app.models import User, Comment, Blog
from app.extensions import db

api = Namespace('comment', description='评论资源')


@api.route('/cid/', '/')
class CommentAPI(Resource):
    def get(self):
        bid = request.form.get('bid')
        blog = Blog.query.get(bid)
        comments = blog.comments.all()
        return ', '.join(c.content for c in comments)

    @auth.login_required
    def delete(self, cid):
        comment = Comment.query.get(cid)
        if g.data['username'] == User.query.get(comment.uid).username:
            db.session.delete(comment)
            return '删除成功'
        return '没有权限删除'


class CommentListAPI(Resource):
    @auth.login_required
    def post(self):
        content = request.form.get('content')
        if content:
            bid = request.form.get('bid')
            user = User.query.filter_by(username=g.data['username']).first()
            comment = Comment(content=content, bid=bid, uid=user.id)
            db.session.add(comment)
            return '评论成功'
        return '评论不能为空'

    def get(self):
        return ''


api.add_resource(CommentListAPI, '/push/')